const { WebSocketServer } = require("ws");

//创建后台WebSocket服务
function createServer(port) { 
  return new Promise((resolve) => { 
    const wss = new WebSocketServer({ port }, () => { 
      resolve(wss);
    })
  })
}

let count = 0;

async function init(port) { 
  const wss = await createServer(port);
  console.log("原生 WebSocket 服务已经启动,端口号:" + port);
  //连接
  wss.on('connection', (socket) => {
    //接收消息，注意回调函数中的message参数是一个buffer对象
    socket.on('message', (message) => {
      console.log("接收来自前端的信息:" + message);
      if (message.toString() === "hello") {
        socket.send("hello,boy");
      }
      else if (message.toString() === "服务器") {
        socket.send("我在呢！")
      }
      else { 
        socket.send("你好啊，我是后台服务");
      } 
    })
  });

  //每隔3秒钟轮询给每个客户端发送信息
  const timer = setInterval(() => {
    count++;
    wss.clients.forEach(ws => { 
      ws.send(`来自服务器的消息:${count}`);
    })
  }, 3000);

  //后端关闭websocket服务触发
  wss.on('close', (e) => {
    clearInterval(timer);
  });
}

init(9527);